# -*- coding: utf-8 -*-
'''
Created on 2012-9-6


@author: Administrator
'''
import locale
import time,datetime
from service.public.service_base import ServiceBase
from helper.login_session_manager import LoginSessionManager
import json
from cgi import parse
from dbwrapper.companyx.shop import Shop
from dbwrapper.companyx.shop_group import ShopGroup
from dbwrapper.companyx.user import User
from dbwrapper.companyx.user_right import UserRight
from dbwrapper.companyx import *
import dbwrapper
from sqlalchemy.orm import class_mapper
from common.debug import Debug

class CompanyService(ServiceBase):
    '''
    company application
  
    '''

    def __init__(self,start_response):
        ServiceBase.__init__(self, start_response)
        self.debug = Debug()

        
    def application(self, params,paths):
        
        #检查 TOKEN 的有效性 
        dbsession =self._returndbsession()
        company_id=params.getfirst("company_id");
        username=params.getfirst("username");
        token=params.getfirst("token");
        intcomp = LoginSessionManager.isValidSession(company_id, username, token, dbsession)
        if intcomp==False:
                return self._responseError(107, 'TOKEN 已经过期')
            
        
        #开始分流  get or set         
        if paths[2] == 'get':
            return self.getfromcompanyx(params)
        elif paths[2] == 'set':
            return self.setConfigApplication(params)
             
             
        
        return self._responseError(-1, "操作失败")


    def getfromcompanyx(self, params):
        '''
            公司X库保存的信息表      
        '''
        #TODO:       
        if params.has_key('type') == False:
            self.debug.e('CompanyService.getfromcompanyx:no \'type\' parameters')
            return self._responseInvalidParam()
        
                
        config_table = params.getfirst('type')
        
        self.debug.d("tablename:%s" % config_table)
        config_table_classes = {}         
        config_table_classes["shop_group"] =shop_group.ShopGroup
        config_table_classes["shop"] = shop.Shop 
        config_table_classes["user_right"] = user_right.UserRight 
        config_table_classes["user"] =user.User 


        config_orderby = {}
        config_orderby["shop_group"] ="id"
        config_orderby["shop"] = "id asc,group_id asc "
        config_orderby["user_right"] = "user_id asc,id asc "
        config_orderby["user"] = "shop_id asc,id asc "
        
        if config_table in config_table_classes:
            table_class = config_table_classes[config_table]
            orderby=config_orderby[config_table]
            return self.getfromcompanyxAction(params, table_class,orderby)
        else:
            return self._responseError(-1, "unkonw configure")
        

    def getfromcompanyxAction(self, params, table_class,orderby):
        '''
                       对读配置的响应
        table_class 要操作的表对应的ORM类
        '''
        try:

            #过滤出要更新的表字段名和字段值
            dbsession =self._returndbsession()
            company_id = params.getfirst('company_id')  
            table_class.doMapping(company_id)                      
            #获取记录操作
            query_result = dbsession.query(table_class).filter().order_by(orderby).all()            
            table_fields = {}                       
            for col in (class_mapper(table_class).mapped_table.c):
                table_fields[col.name]=col.name
                                                                                           

            self.debug.e('CompanyService.getfromcompanyxAction:%s' % repr(table_fields))
                
                             
                
            returnlist=[]                
            dicmy={}
            dicmy["ret"]=0
            dicmy["msg"]='success'
            icount=0                     
            for r in query_result:
                icount=1
                dicmyFF={} 
                for field in  table_fields:
                    temp=getattr(r, table_fields[field])                  
                    if type(temp) is datetime.datetime:
                        dicmyFF[field]=str(temp)                        
                    else:
                        dicmyFF[field]=temp
                
                    
                strtemp=json.dumps(dicmyFF)                
                returnlist.append(strtemp)
                
                
            if icount == 0:
                
                return self._responseError(6, "记录为空")   
            
            dicmy['data']=returnlist
           
            return self._response(json.dumps(dicmy))         
        except Exception, e:
           
            self.debug.e('CompanyService.getfromcompanyxAction(): exception:%s' % e)
            return self._responseInvalidParam()
        

        
        
    def setConfigApplication(self, params):
        '''
                     修改  添加  删除  相关的信息 
        '''
       
        if params.has_key('config_table') == False:
            self.debug.e('CompanyService.setConfigApplication:no \'config_table\' parameters')
            return self._responseInvalidParam()
                        
        config_table = params.getfirst('config_table')
        
        config_table_classes = {}
        config_table_classes["shop_group"] =shop_group.ShopGroup
        config_table_classes["shop"] = shop.Shop
        config_table_classes["user_right"] = user_right.UserRight
        config_table_classes["user"] = user.User
        
        if config_table in config_table_classes:
            table_class = config_table_classes[config_table]
            return self.setConfigAction(params, table_class)
        else:
            return self.response(-1, "unkonw configure")
        


    def setuserrightAction(self, params, table_class): 
        try:
            company_id = params.getfirst('company_id')
            table_class.doMapping(company_id)                          
            dbsession =self._returndbsession()   
            user_id=params.getfirst('user_id')                
            query_result=dbsession.query(table_class).filter(UserRight.user_id == user_id).all()
            for r in query_result:
                dbsession.delete(r)
                dbsession.commit()
                
            right_name=params.getfirst('right_name')
            right_name=right_name[1:-1].split(',')
            for element in right_name:
                table_object = table_class()
                table_object.user_id=user_id
                table_object.right_name=element
                dbsession.add(table_object)
                dbsession.commit()
            
            output = {"ret":0,"msg":"ok"}
            
            return self._response(json.dumps(output))
            
            
        except Exception, e:
          
            self.debug.e("CompanyService.setuserrightAction()failed： %s " % e)
            return self._responseError(-1, "add failed");

                
            
            

 
        
        
        
    def setConfigAction(self, params, table_class):
        '''
        对写配置的响应
        table_class 要操作的表对应的ORM类
        '''
        try:

            cmd = params.getfirst('cmd')
            #过滤出要更新的表字段名和字段值
            exclude_fields = ['company_id','op_shop_id', 'username', 
                              'token', 'cmd', 'config_table', 'where_name', 
                              'where_value', 'sign']
            
            table_fields = {}
            for param in params.keys():
                if param not in exclude_fields:
                    table_fields[param] = params.getfirst(param)
                    
            company_id = params.getfirst('company_id')
            table_class.doMapping(company_id)              
            
            dbsession =self._returndbsession()      
            if cmd == 'add':
                #如果是对权限进行操作
                if (table_class==user_right.UserRight):
                    return self.setuserrightAction(params,table_class)
                
                # 增加记录操作                
                table_object = table_class()
                for field in table_fields:
                    table_object.__setattr__(field, table_fields[field])
                    
                try:
                    dbsession.add(table_object)
                    dbsession.commit()
                except Exception, e:
                    self.debug.e("CompanyService.setConfigAction() add table %s failed" % table_object)
                    
                    return self._responseError(-1, "add failed");
                
               
                output = {"ret":0,"msg":"add ok"}
                return self._response(json.dumps(output))
            elif cmd == 'update':
                #如果是对权限进行操作
                if (table_class==user_right.UserRight):
                    return self.setuserrightAction(params,table_class)

                
                #更新记录操作
                #获取要修改的表where字段
                where_name = params.getfirst('where_name')
                where_value = params.getfirst('where_value')
                #get the column attribute
                columnAttr = getattr(table_class, where_name)
                
                query_result = dbsession.query(table_class).filter(columnAttr == where_value)
                
                if query_result.count() ==0:
                    
                    self.debug.e("CompanyService.setConfigAction(): no such record")
                    return self._responseError(-1, "no such record")
                
                for table_object in query_result:
                    for field in table_fields:
                        table_object.__setattr__(field, table_fields[field])
                        
                dbsession.commit()
                
                output = {'ret':0, 'msg' : 'update ok'}
                return self._response(json.dumps(output))
            elif cmd == 'del':                
                #删除记录操作
                
                where_name = params.getfirst('where_name')
                where_value = params.getfirst('where_value')
                #get the column attribute
                columnAttr = getattr(table_class, where_name)
                
                dbsession.query(table_class).filter(columnAttr == where_value).delete()
                dbsession.commit()
                
                
                output ={'ret':0, 'msg' : 'delete ok'}
                return self._response(json.dumps(output))
        except Exception, e:
            self.debug.e('ShopConfigService.setConfigAction(): exception:%s' % e)
            return self._responseInvalidParam()
        